// parser.js
import _ from "lodash";

import { sendRequest } from "./util";
import React from 'react';
import { Button, Slider, Tree } from 'antd';
import type { TreeDataNode, TreeProps } from 'antd';

export class Game extends React.Component {
  state = {
    scale: 1,
    data: null as any,
  };
  async componentDidMount() {
  }
  async load() {
    var ret = await sendRequest("get-file", { "filename": "e:\\game\\gb2\\mission.scn" });

    var text = ret.text;
    var index = 0;

    function preProcess(obj: any) {
      var s = "";
      var subObjs = [];
      var isStr = false;
      while (true) {
        var c = text[index++];
        if (index > text.length) {
          obj.s = s.trim();
          obj.subObjs = subObjs;
          return;
        }
        if (isStr) {
          if (c == "\"") {
            isStr = false;
          }
          s += c;
        } else {
          if (c == "{") {
            var subObj = {};
            preProcess(subObj);
            subObjs.push(subObj);
          }
          else if (c == "}") {
            obj.s = s.trim();
            obj.subObjs = subObjs;
            return;
          }
          else if (c == "\"") {
            isStr = true;
            s += c;
          } else {
            s += c;
          }
        }
      }
    }

    const proc = (obj: any) => {
      var ret: any[] = [];
      const splitWithQuotes = (str: any) => {
        const regex = /"[^"]*"|'[^']*'|\S+/g;
        const result = [];
        let match;
        while ((match = regex.exec(str)) !== null) {
          result.push(match[0]);
        }
        return result;
      }
      var list = splitWithQuotes(obj.s);
      list.forEach((item) => {
        ret.push(item);
      });
      obj.subObjs.forEach((item: any) => {
        ret.push(proc(item));
      });
      return ret;
    }

    var obj: any = {};
    preProcess(obj);

    obj = proc(obj);

    this.state.data = obj;
    console.log("obj", obj);

    const types: any = {};
    const recurse = (obj: any, func: any) => {
      if (_.isArray(obj)) {
        obj.forEach((item: any) => {
          func(item);
          //recurse(item, func);
        });
      }
    };

    recurse(obj[0], (item: any) => {
      if (!types[item[0]]) {
        types[item[0]] = 0;
      }
      types[item[0]]++;
    });

    console.log("types", types);





    this.setState(this.state);
    return;

    // var flg = false;
    // var filter = (obj: any) => {
    //     obj.forEach((item: any, index: number) => {
    //         if (_.isString(item)) {
    //             if (index >= 3) {
    //                 if (["Orientation", "Position", "xform", "wall"].indexOf(obj[0]) < 0) {
    //                     flg = true; console.log(obj);
    //                 }
    //             }
    //         } else {
    //             filter(item);
    //         }
    //     });
    // };

    // //filter(obj);
    // //console.log(JSON.stringify(obj, null, 2));

    // var convert = (obj: any, index: string) => {
    //     var title = "";
    //     var children: any = [];

    //     obj.forEach((item: any, i: number) => {
    //         if (_.isString(item)) {
    //             title += " " + item;
    //         } else {
    //             if (item[0].toLowerCase() == "player" && _.isString(item[1])) {
    //                 title += " player " + item[1];
    //             } else {
    //                 var r = convert(item, index + "-" + i);
    //                 if (r) {
    //                     children.push(r);
    //                 }
    //             }
    //         }
    //     });
    //     var ret: any = { title, key: index };
    //     if (children.length) {
    //         ret.children = children;
    //     }
    //     return ret;
    // };

    // this.state.treeData = convert(obj, "0").children;
    // this.setState(this.state);
  }
  render() {

    var root = this.state.data ? this.state.data[0] : [];
    var entities: any[] = [];
    var entityNames = new Set();
    root.forEach((item: any) => {
      if (item[0] == "Entity") {
        var entity: any = { name: item[1], id: item[2] };

        if (entity.name.startsWith("\"skirmish")) return;
        entityNames.add(entity.name);
        item.forEach((subItem: any) => {
          if (subItem[0] == "Position") {
            entity.Position = subItem;
          }
          if (subItem[0] == "Player") {
            entity.Player = subItem;
          }
        });

        if (entity.Position && entity.Player) {
          entities.push(entity);
        }
      }

    });
    console.log("entityNames",entityNames);
    var xmin = 99999999;
    var ymin = 99999999;
    var xmax = 0;
    var ymax = 0;

    var scale = 1.0 / Math.pow(Math.E, this.state.scale);

    entities.forEach((entity) => {
      var x = parseFloat(entity.Position[1]);
      var y = parseFloat(entity.Position[2]);
      if (x < xmin) xmin = x;
      if (x > xmax) xmax = x;
      if (y < ymin) ymin = y;
      if (y > ymax) ymax = y;
    });

    entities.forEach((entity) => {
      var x = parseFloat(entity.Position[1]);
      var y = parseFloat(entity.Position[2]);
      entity.x = (x - xmin) * scale;
      entity.y = (y - ymin) * scale;
    });

    var rangex = (xmax - xmin) * scale;
    var rangey = (ymax - ymin) * scale;

    return (
      <>
        <Button onClick={() => { this.load(); }}>load</Button>
        {/* <Tree
                    treeData={this.state.treeData}
                /> */}
        <Slider
          min={1}
          max={5}
          step={0.1}
          onChange={(v: any) => { this.state.scale = v; this.setState(this.state); }}
          value={this.state.scale}
        />
        <div style={{ width: "100%", height: "100%", overflow: "scroll" }}>
          <div style={{ position: "absolute", width: rangex + "px", height: rangey + "px", backgroundColor: "#9FF" }}></div>
          {entities.map((entity) => {
            return <div style={{ position: "absolute", left: entity.x + "px", top: entity.y + "px" }}>{entity.name} {entity.id} {entity.Player[1]}</div>;
          })}
        </div>
      </>
    );
  }
}